package com.hibernate;

import java.util.List;

import org.hibernate.Session;

public class UserManager {

    public static void main(String[] args) throws Exception{
//    	createAndStoreUser();
//    	getUser();
//    	getUserWithQuery();
    	getUserWithCriteria();
    }

    private static void createAndStoreUser() throws Exception{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        for(int i = 11; i < 20; i++){
        	User user = new User();
        	user.setName("user-" + i);
        	user.setPassword("123");
        	user.setEmail("user-" + i + "@mail.com");
        	session.save(user);
//        	if(i == 16){
//        		throw new Exception();
//        	}
        }
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }

    private static void getUser(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        User user = (User)session.get(User.class, 2l);
        System.out.print(user.getId() + ", " + user.getName() + ", " + user.getPassword() + ", " + user.getEmail());
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }
    
    @SuppressWarnings("unchecked")
	private static void getUserWithQuery(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String queryString = "from User";
        List<User> list = session.createQuery(queryString).list();
        for(User user : list){        	
        	System.out.println(user.getId() + ", " + user.getName() + ", " + user.getPassword() + ", " + user.getEmail());
        }
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }
    
    @SuppressWarnings("unchecked")
    private static void getUserWithCriteria(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
		List<User> list = session.createCriteria(User.class).list();
        for(User user : list){        	
        	System.out.println(user.getId() + ", " + user.getName() + ", " + user.getPassword() + ", " + user.getEmail());
        }
        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
    }
}
